import os

import requests


def main():
    load_place = os.path.join(os.getcwd(), '奈学教育')

    if os.path.exists(load_place):
        print('文件夹已存在')
    else:
        os.mkdir('奈学教育')
    url = 'https://1252524126.vod2.myqcloud.com/2919df88vodtranscq1252524126/3871929b387702292499900195/v.f146750.m3u8'
    try:
        m3u8_data = requests.get(url, timeout=9).text
    except Exception as f:
        print('取m3u8文件失败')
        return
    if '#EXTM3U' not in m3u8_data:
        raise BaseException('不是m3u8文件')
    m3u8_li = m3u8_data.split('\n')
    for index, v in enumerate(m3u8_li):
        if '#EXTINF' in v:
            ts_name = m3u8_li[index + 1]
            if os.path.exists(os.path.join(load_place, ts_name)):
                print('ts文件已存在')
                continue
            ts_url = url.rsplit('/', 1)[0] + '/' + ts_name
            while True:
                try:
                    ts_data = requests.get(ts_url, timeout=9).content
                    break
                except Exception:
                    print('取ts数据失败')
            with open(os.path.join(load_place, ts_name), 'wb')as f:
                f.write(ts_data)
                print(f'{ts_name}写入成功1')
    merge(load_place, '奈学day01.mp4')


def merge(path, name):
    os.chdir(path)
    ts_li = os.listdir(path)
    ts_li.sort(key=lambda x: int(x[10:-3]))

    sec = length = len(ts_li)
    if length > 400:
        sec = 400
    li = [ts_li[i:i + sec] for i in range(0, length, sec)]
    cmd_a = ''
    for d, i in enumerate(li):

        cmd = ''
        for index, v in enumerate(i):
            if index == 0:
                cmd = v
            else:
                cmd = cmd + '+' + v
        cmd = f'copy /b {cmd} {name}_{d}'
        os.system(cmd)

        if os.path.exists(f'{name}_{d}'):
            print('中间合并文件成功')
            if d == 0:
                cmd_a = f'{name}_{d}'
            else:
                cmd_a = cmd_a + '+' + f'{name}_{d}'
        else:
            print('中间文件合并失败！')
    cmd = f'copy /b {cmd_a} {name}'
    os.system(cmd)
    if os.path.exists(name):
        os.system('del *.ts')
        os.system('del *_?')
    print('合并文件成功')


if __name__ == '__main__':
    main()
